package apptoko.com.fragment;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import apptoko.com.adapter.BannerSlideFragment;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.event.Event.PageBannerSuccessEvent;
import apptoko.com.model.BannerItem;
import apptoko.com.util.Constants;
import apptoko.com.util.Utils;
import apptoko.com.view.CustomViewPager;

import apptoko.com.R;
import com.viewpagerindicator.CirclePageIndicator;

import de.greenrobot.event.EventBus;

public class ParentBannerSlideFragment extends BaseFragment {
	
	private CustomViewPager bannerPager;
	private List<BannerItem> bannerList;
	private BannerSlideAdapter adapter;
	private String accessToken;
	private BackgroundTasks bgTask;
	private CirclePageIndicator indicator;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mParent = inflater.inflate(R.layout.layout_banner_newsfeed, null);
		indicator = (CirclePageIndicator) mParent.findViewById(R.id.page_indicator);
		bannerPager = (CustomViewPager) mParent.findViewById(R.id.banner_pager);
		return mParent;
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		bannerList = new ArrayList<BannerItem>();
		bgTask = new BackgroundTasks(mContext);
		accessToken = Utils.getStaticAccessToken(getActivity());
		EventBus.getDefault().register(this);
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		bgTask.getBannerByPage(accessToken, Constants.ANDROID_STORE, Constants.NEWSFEED_BANNER_PAGE);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
	
	public void onEventMainThread(PageBannerSuccessEvent event){
		for(BannerItem item : event.getBannerList()){
			bannerList.add(item);
		}
		adapter = new BannerSlideAdapter(getFragmentManager());
		bannerPager.setAdapter(adapter);
		indicator.setViewPager(bannerPager);
		indicator.setFillColor(Color.CYAN);
		indicator.setStrokeColor(Color.GRAY);
		//adapter.notifyDataSetChanged();
	}

	private class BannerSlideAdapter extends FragmentStatePagerAdapter {
		

		public BannerSlideAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// TODO Auto-generated method stub
			BannerSlideFragment frag = new BannerSlideFragment();
			Bundle bun = new Bundle();
			bun.putSerializable(Constants.IMAGES, bannerList.get(position));
			frag.setArguments(bun);
			return frag;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return bannerList.size();
		}
		
	}
}
